package cn.stylefeng.guns.modular.hx.order.service.impl;

import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import cn.hutool.http.HttpRequest;
import cn.stylefeng.guns.core.util.DateUtil2;
import cn.stylefeng.guns.modular.basic.entity.BasicAddress;
import cn.stylefeng.guns.modular.basic.entity.BasicPutgoods;
import cn.stylefeng.guns.modular.basic.model.params.BasicCustomerParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicXlbOauth2tokenParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicCustomerResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicXlbOauth2tokenResult;
import cn.stylefeng.guns.modular.basic.service.*;
import cn.stylefeng.guns.modular.hx.basic.entity.HxBasicGoods;
import cn.stylefeng.guns.modular.hx.order.entity.HxOrderPutDetailed;
import cn.stylefeng.guns.modular.hx.order.model.params.HxOrderOutParam;
import cn.stylefeng.guns.modular.hx.order.model.result.HxOrderOutResult;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageStockParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.entity.BasicWarehouse;
import cn.stylefeng.guns.modular.basic.model.params.BasicAddressParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicPutgoodsParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicPutgoodsResult;
import cn.stylefeng.guns.modular.hx.basic.model.params.HxBasicGoodsParam;
import cn.stylefeng.guns.modular.hx.basic.model.result.HxBasicGoodsResult;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicGoodsService;
import cn.stylefeng.guns.modular.hx.order.entity.HxOrderPut;
import cn.stylefeng.guns.modular.hx.order.entity.HxOrderPutExcelItem;
import cn.stylefeng.guns.modular.hx.order.mapper.HxOrderPutMapper;
import cn.stylefeng.guns.modular.hx.order.model.params.HxOrderPutDetailedParam;
import cn.stylefeng.guns.modular.hx.order.model.params.HxOrderPutParam;
import cn.stylefeng.guns.modular.hx.order.model.result.HxOrderPutResult;
import cn.stylefeng.guns.modular.hx.order.service.HxOrderPutDetailedService;
import  cn.stylefeng.guns.modular.hx.order.service.HxOrderPutService;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStoragePutDetailedParam;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStoragePutParam;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxStoragePutDetailedResult;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxStoragePutResult;
import cn.stylefeng.guns.modular.hx.storage.service.HxStoragePutDetailedService;
import cn.stylefeng.guns.modular.hx.storage.service.HxStoragePutService;
import cn.stylefeng.guns.modular.order.entity.OrderPutExcelItem;
import cn.stylefeng.guns.modular.order.model.params.OrderPutDetailedParam;
import cn.stylefeng.guns.modular.order.model.params.OrderPutParam;
import cn.stylefeng.guns.modular.order.model.result.OrderPutResult;
import cn.stylefeng.guns.sys.modular.system.entity.Dept;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.DeptService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;

/**
 * <p>
 * 入库订单表 服务实现类
 * </p>
 *
 * @author zhucx
 * @since 2023-08-05
 */
@Service
public class HxOrderPutServiceImpl extends ServiceImpl<HxOrderPutMapper, HxOrderPut> implements HxOrderPutService {

    @Override
    public void add(HxOrderPutParam param){
        HxOrderPut entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(HxOrderPutParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(HxOrderPutParam param){
        HxOrderPut oldEntity = getOldEntity(param);
        HxOrderPut newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public HxOrderPutResult findBySpec(HxOrderPutParam param){
        return this.baseMapper.findBySpec(param);
    }

    @Override
    public List<HxOrderPutResult> findListBySpec(HxOrderPutParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(HxOrderPutParam param,String condition,Long operateId){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,condition, operateId);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public LayuiPageInfo findqueryPageBySpec(HxOrderPutParam param,String condition,Long operateId){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customQueryPageList(pageContext, param,condition, operateId);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public LayuiPageInfo findreturnPageBySpec(HxOrderPutParam param,String condition,Long operateId){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customReturnPageList(pageContext, param,condition, operateId);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public LayuiPageInfo findreturnQueryPageBySpec(HxOrderPutParam param,String condition,Long operateId){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customreturnQueryPageList(pageContext, param,condition, operateId);
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(HxOrderPutParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private HxOrderPut getOldEntity(HxOrderPutParam param) {
        return this.getById(getKey(param));
    }

    private HxOrderPut getEntity(HxOrderPutParam param) {
        HxOrderPut entity = new HxOrderPut();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

	@Override
	public boolean saveBatchList(List<HxOrderPutParam> list) {
		return this.baseMapper.saveBatchList(list);
	}

	@Override
	public boolean checkCustomerOrder(String orderPutNumber) {
		return this.baseMapper.checkCustomerOrder(orderPutNumber)==null?false:true;
	}

	@Override
	public HxOrderPut findByThelastone() {
		return this.baseMapper.findByThelastone();
	}

	@Override
	public HxOrderPutResult getPrintOrderPut(HxOrderPutParam param) {
		return this.baseMapper.getPrintOrderPut(param);
	}

	private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            if (DateUtil.isCellDateFormatted(cell)) {
                return HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toString();
            } else {
                return new BigDecimal(Double.toString(cell.getNumericCellValue())).toString();
            }
        } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            return StringUtils.trimToEmpty(cell.getStringCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
            return StringUtils.trimToEmpty(cell.getCellFormula());
        } else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
            return "";
        } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
            return "ERROR";
        } else {
            return cell.toString().trim();
        }
    }

    @Resource
    private BasicCustomerService basicCustomerService;

    @Resource
    private BasicWarehouseService basicWarehouseService;

    @Resource
    private UserService userService;

    @Resource
    private HxBasicGoodsService hxBasicGoodsService;

    @Resource
    private HxOrderPutDetailedService hxOrderPutDetailedService;

    @Resource
    private BasicPutgoodsService basicPutgoodsService;

    @Resource
    private BasicAddressService basicAddressService;
	@Resource
	private BasicXlbOauth2tokenService basicXlbOauth2tokenService;
	@Resource
	private HxOrderPutService hxOrderPutService;

	@Override
	@Transactional(rollbackFor = Exception.class,timeout=300)
	public ResponseData getExceldata(MultipartFile file, HxOrderPutParam hxOrderPutParam, ResponseData data) throws Exception {
		String fileName = file.getOriginalFilename();
		List<HxOrderPutExcelItem> list = new ArrayList<HxOrderPutExcelItem>();

		if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
			data.setMessage("上传文件格式不正确");
			data.setSuccess(false);
        }

		boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);

        for (int r = 1; r <= sheet.getLastRowNum()+1; r++) {
        	Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }
            HxOrderPutExcelItem excelItem = new HxOrderPutExcelItem();

            String  yuyueTime = getCellValue(row.getCell(0));
            if (ToolUtil.isNotEmpty(yuyueTime)) {
                excelItem.setYuyueTime(yuyueTime);
			}

            String orderPutNumber = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(1));
            if (ToolUtil.isNotEmpty(orderPutNumber)) {
                excelItem.setOrderPutNumber(orderPutNumber);
			}

            String  setUnit = getCellValue(row.getCell(2));
            if (ToolUtil.isNotEmpty(setUnit)) {
                excelItem.setSetUnit(setUnit);
			}

            String unitNumber = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(3));
            if (ToolUtil.isNotEmpty(unitNumber)) {
                excelItem.setUnitNumber(unitNumber);
			}

            String goodsNumber = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(4));
            if (ToolUtil.isNotEmpty(goodsNumber)) {
                excelItem.setGoodsNumber(goodsNumber);
			}

            String  goodsName = getCellValue(row.getCell(5));
            if (ToolUtil.isNotEmpty(goodsName)) {
                excelItem.setGoodsName(goodsName);
			}

            String detailedDate = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(6));
            if (ToolUtil.isNotEmpty(detailedDate)) {
                excelItem.setDetailedDate(detailedDate);
			}

            String num = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(7));
            if (ToolUtil.isNotEmpty(num)) {
                excelItem.setNum(num);
			}

            String zpNum = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(8));
            if (ToolUtil.isNotEmpty(zpNum)) {
                excelItem.setZpNum(zpNum);
			}

            String notes = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(9));
            if (ToolUtil.isNotEmpty(notes)) {
                excelItem.setNotes(notes);
			}
            list.add(excelItem);
        }
		List<HxOrderPutParam> olist = new ArrayList<HxOrderPutParam>();//批量保存的 入库订单list
		List<HxOrderPutDetailedParam> detailedList = new ArrayList<HxOrderPutDetailedParam>();//批量保存的 订单商品明细list
		BasicCustomer basicCustomer = basicCustomerService.getById(hxOrderPutParam.getCustomerId());//客户信息
		BasicWarehouse basicWarehouse = basicWarehouseService.getById(hxOrderPutParam.getGetWarehouseId());//仓库信息

    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
		String trayCode = getOperateIdOrderPrefix(user);
		HxOrderPut hxOrderPut = this.findByThelastone();
    	int putNumber = 1;
    	if (hxOrderPut!=null) {
    		putNumber = hxOrderPut.getId()+1;
		}
		for (HxOrderPutExcelItem excelItem : list) {
			if(ToolUtil.isEmpty(excelItem.getSetUnit())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("导入数据中发货客户不得为空!");
				return data;
			}
			if(ToolUtil.isEmpty(excelItem.getGoodsNumber())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("导入数据中商品编号不得为空!");
				return data;
			}
			if(ToolUtil.isEmpty(excelItem.getNum())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("导入数据中数量不得为空!");
				return data;
			}
			BasicPutgoodsParam basicPutgoodsParam = new BasicPutgoodsParam();
			basicPutgoodsParam.setPutgoodsCustomerId(basicCustomer.getId());
			basicPutgoodsParam.setPutgoodsName(excelItem.getSetUnit());
			BasicPutgoodsResult basicPutgoodsResult = basicPutgoodsService.findBySpec(basicPutgoodsParam, null);
			if(basicPutgoodsResult == null) {
				basicPutgoodsParam.setPutgoodsOperateName(basicCustomer.getCustomerName());
				basicPutgoodsParam.setUnitNumber(excelItem.getUnitNumber());
				basicPutgoodsParam.setUnitType("供应商");
				basicPutgoodsParam.setDictId(0l);
				basicPutgoodsParam.setDeptId(user.getDeptId());
				basicPutgoodsParam.setDeliverId(user.getDeliverId());
				basicPutgoodsService.add(basicPutgoodsParam);
				basicPutgoodsResult = basicPutgoodsService.findBySpec(basicPutgoodsParam, null);

				BasicAddressParam addressParam = new BasicAddressParam();
				addressParam.setPutgoodsId(Long.parseLong(basicPutgoodsResult.getId().toString()));//单位id
				addressParam.setAddress(excelItem.getSetUnit());
				addressParam.setPutgoodsName(excelItem.getSetUnit());//单位名称
				addressParam.setSwitchWl("1");
				addressParam.setSwitchBj("1500");//提货围栏半径 默认100米
				addressParam.setSwitchBj2("2000");//收货围栏半径 默认100米
				basicAddressService.add(addressParam);
			}

			//通过 导入的订单号 查询是否存在
			HxOrderPutParam opp = new HxOrderPutParam();
			boolean whether2 = false;
			if(ToolUtil.isEmpty(excelItem.getOrderPutNumber())) {
				whether2 = true;
				excelItem.setOrderPutNumber(trayCode+"RK"+cn.stylefeng.guns.core.util.DateUtil.getDateBch()+(putNumber));
			}
			opp.setOrderPutNumber(excelItem.getOrderPutNumber());//订单号
			HxOrderPutResult oprHxOrderPutResult = this.findBySpec(opp);//状态不等于 作废
			//如果不存在
			if(oprHxOrderPutResult==null) {
				//新增入库订单
		    	opp.setCustomerId(hxOrderPutParam.getCustomerId());//客户id
		    	opp.setCustomerName(basicCustomer.getCustomerName());//客户名称
		    	opp.setOrderState("待提交");//订单状态
		    	opp.setYuyueTime(excelItem.getYuyueTime());
		    	opp.setOrderType(hxOrderPutParam.getOrderType());
		    	opp.setGetWarehouseId(hxOrderPutParam.getGetWarehouseId());//仓库id
		    	opp.setGetWarehouse(basicWarehouse.getWarehouseName());//仓库名称
		    	opp.setSetUnitId(Long.parseLong(basicPutgoodsResult.getId().toString()));
		    	opp.setSetUnit(excelItem.getSetUnit());
		    	opp.setCreateUserName(user.getName());//制单人名称
		    	opp.setCreateTime(new Date());
		    	opp.setNotes(excelItem.getNotes());
		    	opp.setDeliverId(deliverId);//交付id
		    	opp.setDeptId(deptId);//部门id
		    	boolean whether = false;//判断单号  是否重复
		    	for (HxOrderPutParam opp2 : olist) {
					if (opp2.getOrderPutNumber().equals(opp.getOrderPutNumber())) {
						whether = true;
						oprHxOrderPutResult = new HxOrderPutResult();
		    			ToolUtil.copyProperties(opp2,oprHxOrderPutResult);
					}
				}
		    	if (!whether) {
		    		olist.add(opp);
		    		if(!whether2) {
		    			putNumber++;
		    		}
		    		oprHxOrderPutResult = new HxOrderPutResult();
	    			ToolUtil.copyProperties(opp,oprHxOrderPutResult);
				}
    			opp = new HxOrderPutParam();
			} else {
				//如果 导入的客户单号 已存在
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("导入数据中订单号:"+excelItem.getOrderPutNumber()+"已存在!");
				return data;
			}

			HxBasicGoodsParam hxBasicGoodsParam = new HxBasicGoodsParam();
			hxBasicGoodsParam.setGoodsCustomerId(basicCustomer.getId());
			hxBasicGoodsParam.setGoodsNumber(excelItem.getGoodsNumber());
			HxBasicGoodsResult hxBasicGoodsResult = hxBasicGoodsService.findBySpec(hxBasicGoodsParam, null);
			if(hxBasicGoodsResult == null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("导入数据中商品"+excelItem.getGoodsNumber()+"系统不存在!请及时同步");
				return data;
			}

			HxOrderPutDetailedParam hxd = new HxOrderPutDetailedParam();
			BigDecimal num = new BigDecimal(excelItem.getNum()).setScale(3, BigDecimal.ROUND_HALF_DOWN);
			BigDecimal zpNum = new BigDecimal("0");
			BigDecimal sumNum = new BigDecimal(excelItem.getNum()).setScale(3, BigDecimal.ROUND_HALF_DOWN);
			if(ToolUtil.isNotEmpty(excelItem.getZpNum())) {
				zpNum = new BigDecimal(excelItem.getZpNum()).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				sumNum = num.add(zpNum).setScale(3, BigDecimal.ROUND_HALF_DOWN);
			}
			BigDecimal goodsVolume = new BigDecimal(hxBasicGoodsResult.getGoodsVolume());
			BigDecimal goodsWeight = new BigDecimal(hxBasicGoodsResult.getGoodsWeight());
			BigDecimal goodsPrice = new BigDecimal("0");
			BigDecimal goodsSupportvolume = new BigDecimal(hxBasicGoodsResult.getGoodsSupportvolume());
			hxd.setUnitType(hxOrderPutParam.getUnitType());
			if(hxOrderPutParam.getUnitType().equals("采购单位")) {
				hxd.setUnit(hxBasicGoodsResult.getCgUnit());
				hxd.setRate(hxBasicGoodsResult.getCgRate());
				BigDecimal cgRate = new BigDecimal(hxBasicGoodsResult.getCgRate());
				BigDecimal goodsChargingCg = new BigDecimal(hxBasicGoodsResult.getGoodsChargingCg());
				goodsPrice = cgRate.multiply(goodsChargingCg).setScale(3, BigDecimal.ROUND_HALF_DOWN);//换算率*基本单位单价=采购单位单价
			} else if(hxOrderPutParam.getUnitType().equals("配送单位")){
				hxd.setUnit(hxBasicGoodsResult.getPsUnit());
				hxd.setRate(hxBasicGoodsResult.getPsRate());
				BigDecimal psRate = new BigDecimal(hxBasicGoodsResult.getPsRate());
				BigDecimal cgRate = new BigDecimal(hxBasicGoodsResult.getCgRate());
				if(psRate.compareTo(cgRate) == -1) {
					//如果配送换算率 小于 采购换算率：  配送体积  =  采购体积/（采购换算率/配送换算率）
					BigDecimal div = cgRate.divide(psRate,3, BigDecimal.ROUND_HALF_DOWN);
					BigDecimal divv_v = goodsVolume.divide(div,4, BigDecimal.ROUND_HALF_DOWN);
					goodsVolume = divv_v;
					BigDecimal divv_w = goodsWeight.divide(div,3, BigDecimal.ROUND_HALF_DOWN);
					goodsWeight = divv_w;
					BigDecimal divv_s = goodsSupportvolume.multiply(div);
					goodsSupportvolume = divv_s;
				}
				if(psRate.compareTo(cgRate) == 1) {
					//如果配送换算率 大于 采购换算率：  配送体积  =  采购体积*（配送换算率/采购换算率）
					BigDecimal div = psRate.divide(cgRate,3, BigDecimal.ROUND_HALF_DOWN);
					BigDecimal divv_v = goodsVolume.multiply(div).setScale(4, BigDecimal.ROUND_HALF_DOWN);
					goodsVolume = divv_v;
					BigDecimal divv_w = goodsWeight.multiply(div).setScale(3, BigDecimal.ROUND_HALF_DOWN);
					goodsWeight = divv_w;
					BigDecimal divv_s = goodsSupportvolume.divide(div);
					goodsSupportvolume = divv_s;
				}
				BigDecimal goodsChargingCg = new BigDecimal(hxBasicGoodsResult.getGoodsChargingCg());
				goodsPrice = psRate.multiply(goodsChargingCg).setScale(3, BigDecimal.ROUND_HALF_DOWN);
			} else if(hxOrderPutParam.getUnitType().equals("批发单位")) {
				hxd.setUnit(hxBasicGoodsResult.getPfUnit());
				hxd.setRate(hxBasicGoodsResult.getPfRate());
				BigDecimal pfRate = new BigDecimal(hxBasicGoodsResult.getPfRate());
				BigDecimal cgRate = new BigDecimal(hxBasicGoodsResult.getCgRate());
				if(pfRate.compareTo(cgRate) == -1) {
					BigDecimal div = cgRate.divide(pfRate,3, BigDecimal.ROUND_HALF_DOWN);
					BigDecimal divv_v = goodsVolume.divide(div,4, BigDecimal.ROUND_HALF_DOWN);
					goodsVolume = divv_v;
					BigDecimal divv_w = goodsWeight.divide(div,3, BigDecimal.ROUND_HALF_DOWN);
					goodsWeight = divv_w;
					BigDecimal divv_s = goodsSupportvolume.multiply(div);
					goodsSupportvolume = divv_s;
				}
				if(pfRate.compareTo(cgRate) == 1) {
					BigDecimal div = pfRate.divide(cgRate.setScale(3, BigDecimal.ROUND_HALF_DOWN));
					BigDecimal divv_v = goodsVolume.multiply(div).setScale(4, BigDecimal.ROUND_HALF_DOWN);
					goodsVolume = divv_v;
					BigDecimal divv_w = goodsWeight.multiply(div).setScale(3, BigDecimal.ROUND_HALF_DOWN);
					goodsWeight = divv_w;
					BigDecimal divv_s = goodsSupportvolume.divide(div);
					goodsSupportvolume = divv_s;
				}
				BigDecimal goodsChargingPf = new BigDecimal(hxBasicGoodsResult.getGoodsChargingPf());
				goodsPrice = pfRate.multiply(goodsChargingPf).setScale(3, BigDecimal.ROUND_HALF_DOWN);
			} else if(hxOrderPutParam.getUnitType().equals("库存单位")) {
				hxd.setUnit(hxBasicGoodsResult.getKcUnit());
				hxd.setRate(hxBasicGoodsResult.getKcRate());
				BigDecimal kcRate = new BigDecimal(hxBasicGoodsResult.getKcRate());
				BigDecimal cgRate = new BigDecimal(hxBasicGoodsResult.getCgRate());
				if(kcRate.compareTo(cgRate) == -1) {
					BigDecimal div = cgRate.divide(kcRate,3, BigDecimal.ROUND_HALF_DOWN);
					BigDecimal divv_v = goodsVolume.divide(div,4, BigDecimal.ROUND_HALF_DOWN);
					goodsVolume = divv_v;
					BigDecimal divv_w = goodsWeight.divide(div,3, BigDecimal.ROUND_HALF_DOWN);
					goodsWeight = divv_w;
					BigDecimal divv_s = goodsSupportvolume.multiply(div);
					goodsSupportvolume = divv_s;
				}
				if(kcRate.compareTo(cgRate) == 1) {
					BigDecimal div = kcRate.divide(cgRate,3, BigDecimal.ROUND_HALF_DOWN);
					BigDecimal divv_v = goodsVolume.multiply(div).setScale(4, BigDecimal.ROUND_HALF_DOWN);
					goodsVolume = divv_v;
					BigDecimal divv_w = goodsWeight.multiply(div).setScale(3, BigDecimal.ROUND_HALF_DOWN);
					goodsWeight = divv_w;
					BigDecimal divv_s = goodsSupportvolume.divide(div);
					goodsSupportvolume = divv_s;
				}
				BigDecimal goodsChargingCg = new BigDecimal(hxBasicGoodsResult.getGoodsChargingPf());
				goodsPrice = kcRate.multiply(goodsChargingCg).setScale(3, BigDecimal.ROUND_HALF_DOWN);
			}
			//创建订单明细
			hxd.setOrderPutNumber(oprHxOrderPutResult.getOrderPutNumber());
			hxd.setGoodsId(Long.parseLong(hxBasicGoodsResult.getId().toString()));
			hxd.setGoodsName(hxBasicGoodsResult.getGoodsName());
			hxd.setGoodsNumber(hxBasicGoodsResult.getGoodsNumber());
			hxd.setGoodsPcode69(hxBasicGoodsResult.getGoodsPcode69());
			hxd.setGoodsSpecs(hxBasicGoodsResult.getGoodsSpecs());
			hxd.setDismantlingParts(hxBasicGoodsResult.getDismantlingParts());

			hxd.setNum(num.toString());
			hxd.setZpNum(zpNum.toString());
			hxd.setSumNum(sumNum.toString());

			hxd.setGoodsWeight(goodsWeight.toString());
			hxd.setPutWeight(sumNum.multiply(goodsWeight).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
			hxd.setGoodsVolume(goodsVolume.toString());
			hxd.setPutVolume(sumNum.multiply(goodsVolume).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
			hxd.setGoodsPrice(goodsPrice.toString());
			hxd.setPutMoney(sumNum.multiply(goodsPrice).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
			hxd.setGoodsSupportvolume(goodsSupportvolume.toString());
			hxd.setDetailedDate(excelItem.getDetailedDate());
			hxd.setNotes(excelItem.getNotes());

			detailedList.add(hxd);
			hxd = new HxOrderPutDetailedParam();
		}
		if(detailedList.size()>0){
			this.saveBatchList(olist);
			hxOrderPutDetailedService.saveBatchList(detailedList);
		}
		data.setSuccess(true);
		return data;
	}

	@Override
	@Transactional(rollbackFor = Exception.class,timeout=300)
	public ResponseData getExceldataKh(MultipartFile file, HxOrderPutParam hxOrderPutParam, ResponseData data) throws Exception {
		String fileName = file.getOriginalFilename();
		List<HxOrderPutExcelItem> list = new ArrayList<HxOrderPutExcelItem>();

		if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
			data.setMessage("上传文件格式不正确");
			data.setSuccess(false);
		}

		boolean isExcel2003 = true;
		if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
			isExcel2003 = false;
		}
		InputStream is = file.getInputStream();
		Workbook wb = null;
		if (isExcel2003) {
			wb = new HSSFWorkbook(is);
		} else {
			wb = new XSSFWorkbook(is);
		}
		Sheet sheet = wb.getSheetAt(0);

		for (int r = 1; r <= sheet.getLastRowNum()+1; r++) {
			Row row = sheet.getRow(r);
			if (row == null){
				continue;
			}
			HxOrderPutExcelItem excelItem = new HxOrderPutExcelItem();

//			String  yuyueTime = getCellValue(row.getCell(0));
			String  yuyueTime = DateUtil2.getDate();
			if (ToolUtil.isNotEmpty(yuyueTime)) {
				excelItem.setYuyueTime(yuyueTime);
			}

			String orderPutNumber = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(1));
			if (ToolUtil.isNotEmpty(orderPutNumber)) {
				excelItem.setOrderPutNumber(orderPutNumber);
			}

			String unitNumber = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(13));
			if (ToolUtil.isNotEmpty(unitNumber)) {
				excelItem.setUnitNumber(unitNumber);
				excelItem.setSetUnit(unitNumber);
			}

			String goodsNumber = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(4));
			if (ToolUtil.isNotEmpty(goodsNumber)) {
				excelItem.setGoodsNumber(goodsNumber);
			}

			String  goodsName = getCellValue(row.getCell(5));
			if (ToolUtil.isNotEmpty(goodsName)) {
				excelItem.setGoodsName(goodsName);
			}

//			String detailedDate = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(6));
//			if (ToolUtil.isNotEmpty(detailedDate)) {
//				excelItem.setDetailedDate(detailedDate);
//			}

			String num = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(6));
			if (ToolUtil.isNotEmpty(num)) {
				excelItem.setNum(num);
			}

//			String zpNum = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(8));
//			if (ToolUtil.isNotEmpty(zpNum)) {
//				excelItem.setZpNum(zpNum);
//			}

//			String notes = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(9));
//			if (ToolUtil.isNotEmpty(notes)) {
//				excelItem.setNotes(notes);
//			}
			list.add(excelItem);
		}
		List<HxOrderPutParam> olist = new ArrayList<HxOrderPutParam>();//批量保存的 入库订单list
		List<HxOrderPutDetailedParam> detailedList = new ArrayList<HxOrderPutDetailedParam>();//批量保存的 订单商品明细list
		BasicCustomer basicCustomer = basicCustomerService.getById(hxOrderPutParam.getCustomerId());//客户信息
		BasicWarehouse basicWarehouse = basicWarehouseService.getById(hxOrderPutParam.getGetWarehouseId());//仓库信息

		User user = userService.getcurrentUser();
		Long deptId = user.getDeptId();
		Long deliverId = user.getDeliverId();
		String trayCode = getOperateIdOrderPrefix(user);
		HxOrderPut hxOrderPut = this.findByThelastone();
		int putNumber = 1;
		if (hxOrderPut!=null) {
			putNumber = hxOrderPut.getId()+1;
		}
		for (HxOrderPutExcelItem excelItem : list) {
			if(ToolUtil.isEmpty(excelItem.getUnitNumber())) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("导入数据中发货客户不得为空!");
				return data;
			}
			if(ToolUtil.isEmpty(excelItem.getGoodsNumber())) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("导入数据中商品编号不得为空!");
				return data;
			}
			if(ToolUtil.isEmpty(excelItem.getNum())) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("导入数据中数量不得为空!");
				return data;
			}
			BasicPutgoodsParam basicPutgoodsParam = new BasicPutgoodsParam();
			basicPutgoodsParam.setPutgoodsCustomerId(basicCustomer.getId());
			basicPutgoodsParam.setUnitNumber(excelItem.getUnitNumber());
			BasicPutgoodsResult basicPutgoodsResult = basicPutgoodsService.findBySpec(basicPutgoodsParam, null);
			if(basicPutgoodsResult == null) {
				basicPutgoodsParam.setPutgoodsOperateName(basicCustomer.getCustomerName());
				basicPutgoodsParam.setUnitNumber(excelItem.getUnitNumber());
				basicPutgoodsParam.setPutgoodsName(excelItem.getUnitNumber());
				basicPutgoodsParam.setUnitType("供应商");
				basicPutgoodsParam.setDictId(0l);
				basicPutgoodsParam.setDeptId(user.getDeptId());
				basicPutgoodsParam.setDeliverId(user.getDeliverId());
				basicPutgoodsService.add(basicPutgoodsParam);
				basicPutgoodsResult = basicPutgoodsService.findBySpec(basicPutgoodsParam, null);

				BasicAddressParam addressParam = new BasicAddressParam();
				addressParam.setPutgoodsId(Long.parseLong(basicPutgoodsResult.getId().toString()));//单位id
				addressParam.setAddress(excelItem.getUnitNumber());
				addressParam.setPutgoodsName(excelItem.getUnitNumber());//单位名称
				addressParam.setSwitchWl("1");
				addressParam.setSwitchBj("1500");//提货围栏半径 默认100米
				addressParam.setSwitchBj2("2000");//收货围栏半径 默认100米
				basicAddressService.add(addressParam);
			}else{
				excelItem.setSetUnit(basicPutgoodsResult.getPutgoodsName());
			}

			//通过 导入的订单号 查询是否存在
			HxOrderPutParam opp = new HxOrderPutParam();
			boolean whether2 = false;
			if(ToolUtil.isEmpty(excelItem.getOrderPutNumber())) {
				whether2 = true;
				excelItem.setOrderPutNumber(trayCode+"RK"+cn.stylefeng.guns.core.util.DateUtil.getDateBch()+(putNumber));
			}
			opp.setOrderPutNumber(excelItem.getOrderPutNumber());//订单号
			HxOrderPutResult oprHxOrderPutResult = this.findBySpec(opp);//状态不等于 作废
			//如果不存在
			if(oprHxOrderPutResult==null) {
				//新增入库订单
				opp.setCustomerId(hxOrderPutParam.getCustomerId());//客户id
				opp.setCustomerName(basicCustomer.getCustomerName());//客户名称
				opp.setOrderState("待提交");//订单状态
				opp.setYuyueTime(excelItem.getYuyueTime());
				opp.setOrderType(hxOrderPutParam.getOrderType());
				opp.setGetWarehouseId(hxOrderPutParam.getGetWarehouseId());//仓库id
				opp.setGetWarehouse(basicWarehouse.getWarehouseName());//仓库名称
				opp.setSetUnitId(Long.parseLong(basicPutgoodsResult.getId().toString()));
				opp.setSetUnit(excelItem.getSetUnit());
				opp.setCreateUserName(user.getName());//制单人名称
				opp.setCreateTime(new Date());
				opp.setNotes(excelItem.getNotes());
				opp.setDeliverId(deliverId);//交付id
				opp.setDeptId(deptId);//部门id
				boolean whether = false;//判断单号  是否重复
				for (HxOrderPutParam opp2 : olist) {
					if (opp2.getOrderPutNumber().equals(opp.getOrderPutNumber())) {
						whether = true;
						oprHxOrderPutResult = new HxOrderPutResult();
						ToolUtil.copyProperties(opp2,oprHxOrderPutResult);
					}
				}
				if (!whether) {
					olist.add(opp);
					if(!whether2) {
						putNumber++;
					}
					oprHxOrderPutResult = new HxOrderPutResult();
					ToolUtil.copyProperties(opp,oprHxOrderPutResult);
				}
				opp = new HxOrderPutParam();
			} else {
				//如果 导入的客户单号 已存在
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("导入数据中订单号:"+excelItem.getOrderPutNumber()+"已存在!");
				return data;
			}

			HxBasicGoodsParam hxBasicGoodsParam = new HxBasicGoodsParam();
			hxBasicGoodsParam.setGoodsCustomerId(basicCustomer.getId());
			hxBasicGoodsParam.setGoodsNumber(excelItem.getGoodsNumber());
			HxBasicGoodsResult hxBasicGoodsResult = hxBasicGoodsService.findBySpec(hxBasicGoodsParam, null);
			if(hxBasicGoodsResult == null) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("导入数据中商品"+excelItem.getGoodsNumber()+"系统不存在!请及时同步");
				return data;
			}

			HxOrderPutDetailedParam hxd = new HxOrderPutDetailedParam();
			BigDecimal num = new BigDecimal(excelItem.getNum()).setScale(3, BigDecimal.ROUND_HALF_DOWN);
			BigDecimal zpNum = new BigDecimal("0");
			BigDecimal sumNum = new BigDecimal(excelItem.getNum()).setScale(3, BigDecimal.ROUND_HALF_DOWN);
			if(ToolUtil.isNotEmpty(excelItem.getZpNum())) {
				zpNum = new BigDecimal(excelItem.getZpNum()).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				sumNum = num.add(zpNum).setScale(3, BigDecimal.ROUND_HALF_DOWN);
			}
			BigDecimal goodsVolume = new BigDecimal(hxBasicGoodsResult.getGoodsVolume());
			BigDecimal goodsWeight = new BigDecimal(hxBasicGoodsResult.getGoodsWeight());
			BigDecimal goodsPrice = new BigDecimal("0");
			BigDecimal goodsSupportvolume = new BigDecimal(hxBasicGoodsResult.getGoodsSupportvolume());
			hxd.setUnitType(hxOrderPutParam.getUnitType());
			if(hxOrderPutParam.getUnitType().equals("采购单位")) {
				hxd.setUnit(hxBasicGoodsResult.getCgUnit());
				hxd.setRate(hxBasicGoodsResult.getCgRate());
				BigDecimal cgRate = new BigDecimal(hxBasicGoodsResult.getCgRate());
				BigDecimal goodsChargingCg = new BigDecimal(hxBasicGoodsResult.getGoodsChargingCg());
				goodsPrice = cgRate.multiply(goodsChargingCg).setScale(3, BigDecimal.ROUND_HALF_DOWN);//换算率*基本单位单价=采购单位单价
			} else if(hxOrderPutParam.getUnitType().equals("配送单位")){
				hxd.setUnit(hxBasicGoodsResult.getPsUnit());
				hxd.setRate(hxBasicGoodsResult.getPsRate());
				BigDecimal psRate = new BigDecimal(hxBasicGoodsResult.getPsRate());
				BigDecimal cgRate = new BigDecimal(hxBasicGoodsResult.getCgRate());
				if(psRate.compareTo(cgRate) == -1) {
					//如果配送换算率 小于 采购换算率：  配送体积  =  采购体积/（采购换算率/配送换算率）
					BigDecimal div = cgRate.divide(psRate,3, BigDecimal.ROUND_HALF_DOWN);
					BigDecimal divv_v = goodsVolume.divide(div,4, BigDecimal.ROUND_HALF_DOWN);
					goodsVolume = divv_v;
					BigDecimal divv_w = goodsWeight.divide(div,3, BigDecimal.ROUND_HALF_DOWN);
					goodsWeight = divv_w;
					BigDecimal divv_s = goodsSupportvolume.multiply(div);
					goodsSupportvolume = divv_s;
				}
				if(psRate.compareTo(cgRate) == 1) {
					//如果配送换算率 大于 采购换算率：  配送体积  =  采购体积*（配送换算率/采购换算率）
					BigDecimal div = psRate.divide(cgRate,3, BigDecimal.ROUND_HALF_DOWN);
					BigDecimal divv_v = goodsVolume.multiply(div).setScale(4, BigDecimal.ROUND_HALF_DOWN);
					goodsVolume = divv_v;
					BigDecimal divv_w = goodsWeight.multiply(div).setScale(3, BigDecimal.ROUND_HALF_DOWN);
					goodsWeight = divv_w;
					BigDecimal divv_s = goodsSupportvolume.divide(div);
					goodsSupportvolume = divv_s;
				}
				BigDecimal goodsChargingCg = new BigDecimal(hxBasicGoodsResult.getGoodsChargingCg());
				goodsPrice = psRate.multiply(goodsChargingCg).setScale(3, BigDecimal.ROUND_HALF_DOWN);
			} else if(hxOrderPutParam.getUnitType().equals("批发单位")) {
				hxd.setUnit(hxBasicGoodsResult.getPfUnit());
				hxd.setRate(hxBasicGoodsResult.getPfRate());
				BigDecimal pfRate = new BigDecimal(hxBasicGoodsResult.getPfRate());
				BigDecimal cgRate = new BigDecimal(hxBasicGoodsResult.getCgRate());
				if(pfRate.compareTo(cgRate) == -1) {
					BigDecimal div = cgRate.divide(pfRate,3, BigDecimal.ROUND_HALF_DOWN);
					BigDecimal divv_v = goodsVolume.divide(div,4, BigDecimal.ROUND_HALF_DOWN);
					goodsVolume = divv_v;
					BigDecimal divv_w = goodsWeight.divide(div,3, BigDecimal.ROUND_HALF_DOWN);
					goodsWeight = divv_w;
					BigDecimal divv_s = goodsSupportvolume.multiply(div);
					goodsSupportvolume = divv_s;
				}
				if(pfRate.compareTo(cgRate) == 1) {
					BigDecimal div = pfRate.divide(cgRate.setScale(3, BigDecimal.ROUND_HALF_DOWN));
					BigDecimal divv_v = goodsVolume.multiply(div).setScale(4, BigDecimal.ROUND_HALF_DOWN);
					goodsVolume = divv_v;
					BigDecimal divv_w = goodsWeight.multiply(div).setScale(3, BigDecimal.ROUND_HALF_DOWN);
					goodsWeight = divv_w;
					BigDecimal divv_s = goodsSupportvolume.divide(div);
					goodsSupportvolume = divv_s;
				}
				BigDecimal goodsChargingPf = new BigDecimal(hxBasicGoodsResult.getGoodsChargingPf());
				goodsPrice = pfRate.multiply(goodsChargingPf).setScale(3, BigDecimal.ROUND_HALF_DOWN);
			} else if(hxOrderPutParam.getUnitType().equals("库存单位")) {
				hxd.setUnit(hxBasicGoodsResult.getKcUnit());
				hxd.setRate(hxBasicGoodsResult.getKcRate());
				BigDecimal kcRate = new BigDecimal(hxBasicGoodsResult.getKcRate());
				BigDecimal cgRate = new BigDecimal(hxBasicGoodsResult.getCgRate());
				if(kcRate.compareTo(cgRate) == -1) {
					BigDecimal div = cgRate.divide(kcRate,3, BigDecimal.ROUND_HALF_DOWN);
					BigDecimal divv_v = goodsVolume.divide(div,4, BigDecimal.ROUND_HALF_DOWN);
					goodsVolume = divv_v;
					BigDecimal divv_w = goodsWeight.divide(div,3, BigDecimal.ROUND_HALF_DOWN);
					goodsWeight = divv_w;
					BigDecimal divv_s = goodsSupportvolume.multiply(div);
					goodsSupportvolume = divv_s;
				}
				if(kcRate.compareTo(cgRate) == 1) {
					BigDecimal div = kcRate.divide(cgRate,3, BigDecimal.ROUND_HALF_DOWN);
					BigDecimal divv_v = goodsVolume.multiply(div).setScale(4, BigDecimal.ROUND_HALF_DOWN);
					goodsVolume = divv_v;
					BigDecimal divv_w = goodsWeight.multiply(div).setScale(3, BigDecimal.ROUND_HALF_DOWN);
					goodsWeight = divv_w;
					BigDecimal divv_s = goodsSupportvolume.divide(div);
					goodsSupportvolume = divv_s;
				}
				BigDecimal goodsChargingCg = new BigDecimal(hxBasicGoodsResult.getGoodsChargingPf());
				goodsPrice = kcRate.multiply(goodsChargingCg).setScale(3, BigDecimal.ROUND_HALF_DOWN);
			}
			//创建订单明细
			hxd.setOrderPutNumber(oprHxOrderPutResult.getOrderPutNumber());
			hxd.setGoodsId(Long.parseLong(hxBasicGoodsResult.getId().toString()));
			hxd.setGoodsName(hxBasicGoodsResult.getGoodsName());
			hxd.setGoodsNumber(hxBasicGoodsResult.getGoodsNumber());
			hxd.setGoodsPcode69(hxBasicGoodsResult.getGoodsPcode69());
			hxd.setGoodsSpecs(hxBasicGoodsResult.getGoodsSpecs());
			hxd.setDismantlingParts(hxBasicGoodsResult.getDismantlingParts());

			hxd.setNum(num.toString());
			hxd.setZpNum(zpNum.toString());
			hxd.setSumNum(sumNum.toString());

			hxd.setGoodsWeight(goodsWeight.toString());
			hxd.setPutWeight(sumNum.multiply(goodsWeight).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
			hxd.setGoodsVolume(goodsVolume.toString());
			hxd.setPutVolume(sumNum.multiply(goodsVolume).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
			hxd.setGoodsPrice(goodsPrice.toString());
			hxd.setPutMoney(sumNum.multiply(goodsPrice).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
			hxd.setGoodsSupportvolume(goodsSupportvolume.toString());
			hxd.setDetailedDate(excelItem.getDetailedDate());
			hxd.setNotes(excelItem.getNotes());

			detailedList.add(hxd);
//			hxd = new HxOrderPutDetailedParam();
		}
		if(detailedList.size()>0){
			this.saveBatchList(olist);
			hxOrderPutDetailedService.saveBatchList(detailedList);
		}
		data.setSuccess(true);
		return data;
	}

	@Resource
    private DeptService deptService;

	/**
	 * 获取所属项目单号前缀
	 * @param user
	 * @return
	 */
	public String getOperateIdOrderPrefix(User user) {
		if(user.getOperateId() != null) {
			Dept dept = new Dept();
			dept.setOperateId(user.getOperateId());
			Dept resdept = deptService.findBySpec(dept);
			if(resdept != null) {
				if(ToolUtil.isNotEmpty(resdept.getOrderPrefix())) {
					return resdept.getOrderPrefix();
				} else {
					return user.getAccount().substring(0, 3);
				}
			} else {
				return null;
			}
		} else {
			return null;
		}
	}

	@Resource
    private HxStoragePutService hxStoragePutService;

	@Resource
    private HxStoragePutDetailedService hxStoragePutDetailedService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public ResponseData revoke(HxOrderPut hxOrderPut, ResponseData data) {
		HxOrderPutParam hxOrderPutParam = new HxOrderPutParam();
		hxOrderPutParam.setId(hxOrderPut.getId());
		hxOrderPutParam.setOrderState("撤回");
		this.update(hxOrderPutParam);//撤回入库订单

		HxStoragePutParam hxStoragePutParam = new HxStoragePutParam();
		hxStoragePutParam.setStorageNumber(hxOrderPut.getOrderPutNumber());
		HxStoragePutResult hxStoragePutResult = hxStoragePutService.findBySpec(hxStoragePutParam);//查询入库单
		if(hxStoragePutResult.getStorageState().equals("已完成")) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
			data.setSuccess(false);
			data.setMessage("已收货无法撤回!");
			return data;
		} else {
			hxStoragePutParam.setId(hxStoragePutResult.getId());
			hxStoragePutService.delete(hxStoragePutParam);//删除入库单
		}

		HxStoragePutDetailedParam hxStoragePutDetailedParam = new HxStoragePutDetailedParam();
		hxStoragePutDetailedParam.setStorageNumber(hxStoragePutResult.getStorageNumber());
		List<HxStoragePutDetailedResult> list = hxStoragePutDetailedService.findListBySpec(hxStoragePutDetailedParam);
		for (HxStoragePutDetailedResult i : list) {
			if(i.getPutState().equals("待质检")) {
				hxStoragePutDetailedParam.setId(i.getId());
				hxStoragePutDetailedService.delete(hxStoragePutDetailedParam);
			} else {
	            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("已收货无法撤回!");
				return data;
			}
		}
		return ResponseData.success();
	}
	//新零帮入库申请单
	@Override
	@Transactional(rollbackFor = Exception.class,timeout=800000)
	public void taskAppointment() {

		BasicCustomerParam param = new BasicCustomerParam();
		List<BasicCustomerResult> basicCustomerResult = basicCustomerService.findpullYuyueXlbListBySpec(param);
		for (BasicCustomerResult r : basicCustomerResult) {
		if (ToolUtil.isNotEmpty(r.getXlbStorehouseId())) {
			Date date = new Date();
			LocalDateTime currentTime = LocalDateTime.now().minusHours(6);

			// 格式化为需要的日期时间字符串
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
			String formattedDateTime = currentTime.format(formatter);
			LocalDateTime now = LocalDateTime.now();
			String currentFormattedDateTime = now.format(formatter);
			//System.out.println(formattedDateTime);
			List<String> update_times = new ArrayList<String>();
			update_times.add(formattedDateTime);
			update_times.add(currentFormattedDateTime);

			//	String url = "https://test-api.xlbsoft.com/api/hxl.open.wms.inapplicationorder.findbyupdatetime";
			String url = "https://hxl-api.xlbsoft.com/api/hxl.open.wms.inapplicationorder.findbyupdatetime";


			JSONObject json = new JSONObject();
			json.put("store_id", r.getStoreIdXlb());
			json.put("storehouse_id", r.getXlbStorehouseId());
			json.put("update_times", update_times);

//		JSONObject json = new JSONObject();
//		json.put("store_id","100000000005");
//		json.put("storehouse_id", "100000000370");
//		json.put("update_time", modified_yuyue);
			BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
			oauth2tokenParam.setDeliverId(r.getDeliverId());
			oauth2tokenParam.setGsnumber(r.getGsnumber());
			BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);

			String response = HttpRequest.post(url)
					.header("Authorization", "Bearer " + oauth2tokenResult.getOauth2TokenXlb())
					.body(json.toString()).execute().body();
			JSONObject jsonObject = new JSONObject(response);
			//System.out.println(json.toString());
			if (jsonObject.get("code").toString().equals("0")) {
				JSONArray dataArray = jsonObject.getJSONArray("data");
				// 查回来一个集合，通过遍历集合数据，将数据同步到入库订单表中。
				// 然后通过确认续约任务接口，可以来选择是否确认预约到货

				List <Object> dataList = new ArrayList <>();
				for (int i = 0; i < dataArray.length(); i++) {
					Object item = dataArray.get(i);
					dataList.add(item);
				}

				List <HxOrderPut> hxOrderPutList = new ArrayList();
				List <HxOrderPutDetailed> hxOrderPutDetailedList = new ArrayList();
				for (Object data : dataList) {
					HxOrderPut hxOrderPutParam = new HxOrderPut();
					Object fid = ((JSONObject) data).get("fid");// 单据号
					Object orderFid = ((JSONObject) data).get("order_fid");// 关联单据号
					Object appointTime = ((JSONObject) data).get("appointment_date");// 预约送达时间
					Object createBy = ((JSONObject) data).get("create_by");// 制单人
					Object createTime = ((JSONObject) data).get("create_time");// 制单时间
					Object itemCount = ((JSONObject) data).get("item_count");// 商品数
					Object quantity = ((JSONObject) data).get("quantity");// 发货数量
					Object storeId = ((JSONObject) data).get("store_id");// 收货门店id
					Object storeName = ((JSONObject) data).get("store_name");// 收货门店名称
					Object storehouseId = ((JSONObject) data).get("storehouse_id");// 收货仓库id
					Object storehouseName = ((JSONObject) data).get("storehouse_name");// 收货仓库名称
					Object clientId = ((JSONObject) data).get("client_id");// 发货供应商id
					Object clientName = ((JSONObject) data).get("client_name");// 发货供应商名称
					Object orderType = ((JSONObject) data).get("order_type");// 单据类型
					Object meno = ((JSONObject) data).get("memo");// 单据类型

					JSONArray details = ((JSONObject) data).getJSONArray("details");// 明细


					for (Object details1s : details) {
						HxOrderPutDetailed hxOrderPutDetailedParam = new HxOrderPutDetailed();
						Object basicUnit = ((JSONObject) details1s).get("basic_unit");//基本单位

						Object basicVolume = ((JSONObject) details1s).get("basic_volume");//基本单位体积

						Object categoryId = ((JSONObject) details1s).get("category_id");//商品分类id
						Object categoryName = ((JSONObject) details1s).get("category_name");//商品分类名称


						Object dateInType = ((JSONObject) details1s).get("date_in_type");//日期录入规则
						Object deliveryRatio = ((JSONObject) details1s).get("delivery_ratio");//配送单位换算率
						Object deliveryUnit = ((JSONObject) details1s).get("delivery_unit");//配送单位
						Object presentInQuantity = ((JSONObject) details1s).get("present_in_quantity");//实收赠品数量
						Object presentQuantity = ((JSONObject) details1s).get("present_quantity");//申请赠品数量
						Object presentRatio = ((JSONObject) details1s).get("present_ratio");//赠品换算率
						Object presentUnit = ((JSONObject) details1s).get("present_unit");//赠品单位
						Object presentVolume = ((JSONObject) details1s).get("present_volume");//赠品体积
						Object inQuantity = ((JSONObject) details1s).get("in_quantity");//入库数量
						Object purchaseRatio = ((JSONObject) details1s).get("purchase_ratio");//采购单位换算率
						Object purchaseUnit = ((JSONObject) details1s).get("purchase_unit");//采购单位
						Object quantity1 = ((JSONObject) details1s).get("quantity");//申请数量
						Object unit = ((JSONObject) details1s).get("unit");//单位
						Object ratio = ((JSONObject) details1s).get("ratio");//换算率
						Object volume = ((JSONObject) details1s).get("volume");//体积
						Object wholesaleRatio = ((JSONObject) details1s).get("wholesale_ratio");//批发单位换算率
						Object wholesaleUnit = ((JSONObject) details1s).get("wholesale_unit");//批发单位
						Object stockRatio = ((JSONObject) details1s).get("stock_ratio");//库存单位换算率
						Object stockUnit = ((JSONObject) details1s).get("stock_unit");//库存单位

						Object itemBarCode = ((JSONObject) details1s).get("item_bar_code");//商品条码
						Object itemCode = ((JSONObject) details1s).get("item_code");//商品代码
						Object itemId = ((JSONObject) details1s).get("item_id");//商品id
						Object itemName = ((JSONObject) details1s).get("item_name");//商品名称
						Object itemSpec = ((JSONObject) details1s).get("item_spec");//商品规格
						Object memo = ((JSONObject) details1s).get("memo");//备注
						HxBasicGoodsParam hxBasicGoodsParamS = new HxBasicGoodsParam();
						hxBasicGoodsParamS.setGoodsXlbId(itemId.toString());
						hxBasicGoodsParamS.setGoodsCustomerId(r.getId());
						HxBasicGoodsResult goodsid = hxBasicGoodsService.findBySpec(hxBasicGoodsParamS,  r.getCustomerOperateId().longValue());
//					HxBasicGoods goodsid = hxBasicGoodsService.lambdaQuery()
//									.eq(HxBasicGoods::getGoodsXlbId, itemId)
//									.one();
						if (goodsid == null) {
							HxBasicGoods hxBasicGoodsParam = new HxBasicGoods();
							if (ToolUtil.isNotEmpty(itemId.toString()) && !itemId.toString().equals("null")) {
								hxBasicGoodsParam.setGoodsXlbId(itemId.toString());
							}
							if (ToolUtil.isNotEmpty(itemName.toString()) && !itemName.toString().equals("null")) {
								hxBasicGoodsParam.setGoodsName(itemName.toString());
							}
							if (ToolUtil.isNotEmpty(itemBarCode.toString()) && !itemBarCode.toString().equals("null")) {
								hxBasicGoodsParam.setGoodsPcode69(itemBarCode.toString());
							}
							if (ToolUtil.isNotEmpty(itemCode.toString()) && !itemCode.toString().equals("null")) {
								hxBasicGoodsParam.setGoodsNumber(itemCode.toString());

							}
							if (ToolUtil.isNotEmpty(itemSpec.toString()) && !itemSpec.toString().equals("null")) {
								hxBasicGoodsParam.setGoodsSpecs(itemSpec.toString());
							}
							if (ToolUtil.isNotEmpty(basicUnit.toString()) && !basicUnit.toString().equals("null")) {
								hxBasicGoodsParam.setJibenUnit(basicUnit.toString());
							}
							if (ToolUtil.isNotEmpty(stockUnit.toString()) && !stockUnit.toString().equals("null")) {

								hxBasicGoodsParam.setKcUnit(stockUnit.toString());
							}
							if (ToolUtil.isNotEmpty(stockRatio.toString()) && !stockRatio.toString().equals("null")) {
								hxBasicGoodsParam.setKcRate(String.valueOf(stockRatio));
							}
							if (ToolUtil.isNotEmpty(purchaseUnit.toString()) && !purchaseUnit.toString().equals("null")) {
								hxBasicGoodsParam.setCgUnit(purchaseUnit.toString());
							}
							if (ToolUtil.isNotEmpty(purchaseRatio.toString()) && !purchaseRatio.toString().equals("null")) {
								hxBasicGoodsParam.setCgRate(String.valueOf(purchaseRatio));
							}
							hxBasicGoodsParam.setPfRate(String.valueOf(wholesaleRatio));
							hxBasicGoodsParam.setPfUnit(wholesaleUnit.toString());
							hxBasicGoodsParam.setPsRate(String.valueOf(deliveryRatio));
							hxBasicGoodsParam.setPsUnit(deliveryUnit.toString());
							hxBasicGoodsParam.setCreateTime(new Date());
							hxBasicGoodsParam.setCreateName("系统");
							hxBasicGoodsParam.setDeliverId(r.getDeliverId());
							hxBasicGoodsParam.setDeptId(r.getDeptId());
							hxBasicGoodsParam.setGoodsCustomerName(r.getCustomerName());
							hxBasicGoodsParam.setGoodsCustomerId(r.getId());
							hxBasicGoodsParam.setGoodsBottom("10");
							hxBasicGoodsParam.setGoodsLamination("10");
							hxBasicGoodsParam.setGoodsTraylayer("1");
							hxBasicGoodsParam.setGoodsSupportvolume("100");
							hxBasicGoodsParam.setAnquanNum("14");
							hxBasicGoodsParam.setGoodsWeight("0.1");
							hxBasicGoodsParam.setGoodsChargingCg("10");
							hxBasicGoodsParam.setGoodsChargingPf("10");
							hxBasicGoodsParam.setGoodsChargingPs("10");
							hxBasicGoodsParam.setDismantlingParts("否");
							hxBasicGoodsParam.setGoodsBigtypedictId((long) categoryId);
							hxBasicGoodsParam.setGoodsBigtype(categoryName.toString());

							if (ToolUtil.isNotEmpty(basicVolume.toString()) && !basicVolume.toString().equals("null")) {
								hxBasicGoodsParam.setGoodsVolume(basicVolume.toString());
							} else {
								hxBasicGoodsParam.setGoodsVolume("0.1");
							}
							hxBasicGoodsParam.setGoodsWarranty("36");
							hxBasicGoodsService.save(hxBasicGoodsParam);
//							HxBasicGoodsParam hxBasicGoodsParam1 = new HxBasicGoodsParam();
//							hxBasicGoodsParam1.setGoodsXlbId(itemId.toString());
//							hxBasicGoodsParam1.setGoodsCustomerId(r.getId());
//							HxBasicGoodsResult goodsResult = hxBasicGoodsService.findBySpec(hxBasicGoodsParam1, r.getCustomerOperateId().longValue());
//
//							hxOrderPutDetailedParam.setGoodsId(goodsResult.getId().longValue());
							hxOrderPutDetailedParam.setGoodsId(hxBasicGoodsParam.getId().longValue());
						} else {
							hxOrderPutDetailedParam.setGoodsId(goodsid.getId().longValue());
						}


						hxOrderPutDetailedParam.setOrderPutNumber(String.valueOf(fid));
						hxOrderPutDetailedParam.setGoodsName(itemName.toString());
						hxOrderPutDetailedParam.setGoodsSpecs(itemSpec.toString());
						hxOrderPutDetailedParam.setGoodsPcode69(itemBarCode.toString());
						hxOrderPutDetailedParam.setGoodsNumber(itemCode.toString());
						hxOrderPutDetailedParam.setUnit(unit.toString());
						hxOrderPutDetailedParam.setRate(String.valueOf(purchaseRatio));
						hxOrderPutDetailedParam.setNotes(memo.toString());


						BigDecimal decimal = new BigDecimal(purchaseRatio.toString());
						BigDecimal bigDecimal = new BigDecimal(quantity1.toString());
						BigDecimal ratio1 = new BigDecimal(ratio.toString());
						BigDecimal multiply = ratio1.multiply(bigDecimal);
						BigDecimal divide = multiply.divide(decimal, 4, RoundingMode.HALF_DOWN);

						BigDecimal bigDecima2 = new BigDecimal(presentQuantity.toString());

						BigDecimal decimal1 = new BigDecimal(presentRatio.toString());
						BigDecimal multiply1 = ratio1.multiply(bigDecima2);
						BigDecimal divide1 = multiply1.divide(decimal, 4, RoundingMode.HALF_DOWN);
						Double sumNum = Double.parseDouble(String.valueOf(divide)) + Double.parseDouble(String.valueOf(divide1));
						hxOrderPutDetailedParam.setSumNum(String.valueOf(sumNum));
						Double jibenNumSum = Double.parseDouble(String.valueOf(multiply))+Double.parseDouble(String.valueOf(multiply1));

						hxOrderPutDetailedParam.setJibenNum(jibenNumSum.toString());
						hxOrderPutDetailedParam.setJibenUnit(basicUnit.toString());
						if (ToolUtil.isNotEmpty(volume.toString()) && !volume.toString().equals("null")) {
							BigDecimal volume1 = new BigDecimal(volume.toString());
							BigDecimal nums = new BigDecimal(1000000);

							BigDecimal result = volume1.divide(nums, 4, RoundingMode.HALF_DOWN);


							hxOrderPutDetailedParam.setGoodsVolume(result.toString());
							hxOrderPutDetailedParam.setPutVolume(result.toString());
						}
						hxOrderPutDetailedParam.setNum(String.valueOf(divide));
						hxOrderPutDetailedParam.setZpNum(String.valueOf(divide1));
						hxOrderPutDetailedParam.setZpRate(String.valueOf(presentRatio));
						hxOrderPutDetailedParam.setZpUnit(String.valueOf(presentUnit));
						hxOrderPutDetailedParam.setZpJibenNum(divide1.multiply(new BigDecimal(presentRatio.toString())).toString());

						hxOrderPutDetailedParam.setGoodsSupportvolume("100");
						hxOrderPutDetailedParam.setGoodsWeight("0.1");
						hxOrderPutDetailedParam.setGoodsPrice("10");
						hxOrderPutDetailedParam.setUnitType("采购单位");
						hxOrderPutDetailedParam.setXlbOrderPutNumber(String.valueOf(orderFid));

						if (ToolUtil.isNotEmpty(fid) && !fid.equals("null")) {//单据号
							// 校验是否已经添加过
							Integer count = hxOrderPutDetailedService.lambdaQuery()
									.eq(HxOrderPutDetailed::getOrderPutNumber, fid)
									.count();
							if (count == (int) itemCount) {
								continue; // 如果数据库中已存在该订单号，则跳过当前循环
							}
						}
						hxOrderPutDetailedList.add(hxOrderPutDetailedParam);


						this.hxOrderPutDetailedService.saveBatch(hxOrderPutDetailedList);
						hxOrderPutDetailedList.clear();

					}

					if (ToolUtil.isNotEmpty(fid) && !fid.equals("null")) {//单据号
						// 校验是否已经添加过
						Integer count = hxOrderPutService.lambdaQuery()
								.eq(HxOrderPut::getOrderPutNumber, fid)
								.ne(HxOrderPut::getOrderState, "作废")
								.count();
						if (count > 0) {
							continue; // 如果数据库中已存在该订单号，则跳过当前循环
						}
					}
					hxOrderPutParam.setOrderPutNumber(String.valueOf(fid));

					hxOrderPutParam.setYuyueTime(appointTime.toString());// 预约时间

					BasicPutgoods basicPutgoods = basicPutgoodsService.lambdaQuery()
							.eq(BasicPutgoods::getPutgoodsCustomerId, r.getId())
							.eq(BasicPutgoods::getXlbClientId, clientId.toString())
							.eq(BasicPutgoods::getPutgoodsName, clientName.toString())
							.last("limit 1")
							.one();

					BasicWarehouse basicWarehouse = basicWarehouseService.lambdaQuery()
							.eq(BasicWarehouse::getWarehouseOperateId,r.getCustomerOperateId())
							.eq(BasicWarehouse::getWarehouseXlbId, storehouseId.toString())
							.last("limit 1")
							.one();


					if (basicPutgoods == null) {
						BasicPutgoods bpgp3 = new BasicPutgoods();
						bpgp3.setPutgoodsCustomerId(r.getId());
						bpgp3.setPutgoodsOperateName(r.getCustomerName());
						bpgp3.setPutgoodsName(clientName.toString());//单位名称
						bpgp3.setPutgoodsAddress(clientName.toString());
						bpgp3.setXlbClientId(clientId.toString());
						bpgp3.setUnitType("供应商");
						bpgp3.setDictId(0l);
						bpgp3.setDeliverId(r.getDeliverId());
						bpgp3.setDeptId(r.getDeptId());

						basicPutgoodsService.save(bpgp3);

						BasicAddress bap3 = new BasicAddress();

						bap3.setAddress(clientName.toString());//地点 为单位名称
						bap3.setPutgoodsName(clientName.toString());//单位名称
						bap3.setLongitude("0");
						bap3.setLatitude("0");
						bap3.setSwitchWl("1");
						bap3.setSwitchBj("1500");//提货围栏半径 默认100米
						bap3.setSwitchBj2("2000");//收货围栏半径 默认100米
						basicAddressService.save(bap3);

						hxOrderPutParam.setSetUnitId((long) bpgp3.getId());// 发货客户id
					} else {
						hxOrderPutParam.setSetUnitId((long) basicPutgoods.getId());// 发货客户id
					}

					hxOrderPutParam.setSetUnit(clientName.toString());//发货客户
					hxOrderPutParam.setGetWarehouse(storehouseName.toString());// 收货仓库名称
					hxOrderPutParam.setGetWarehouseId((long) basicWarehouse.getId());//收货仓库id
					hxOrderPutParam.setGoodsNum(itemCount.toString());//商品数

					hxOrderPutParam.setCreateTime(date);// 创建时间

					if (orderType.toString().equals("RECEIVE")) {
						hxOrderPutParam.setOrderType("采购收货");
					}
					if (orderType.toString().equals("STORE_IN")) {
						hxOrderPutParam.setOrderType("门店调入");
					}
					if (orderType.toString().equals("WHOLESALE_RETURN")) {
						hxOrderPutParam.setOrderType("批发退货");
					}
					if (orderType.toString().equals("ADJUST_IN")) {
						hxOrderPutParam.setOrderType("调整入库");
					}
					if (orderType.toString().equals("DUMP_IN")) {
						hxOrderPutParam.setOrderType("甩货入库");
					}
					if (orderType.toString().equals("TRANSFER")) {
						hxOrderPutParam.setOrderType("仓间调拨");
					}
					hxOrderPutParam.setOrderState("待提交");
					hxOrderPutParam.setNotes(meno.toString());// 备注

					hxOrderPutParam.setCreateUserName("系统");
					hxOrderPutParam.setXlbOrderId(String.valueOf(orderFid));
					hxOrderPutParam.setDeptId(r.getDeptId());
					hxOrderPutParam.setDeliverId(r.getDeliverId());
					hxOrderPutParam.setCustomerId((long) r.getId());
					hxOrderPutParam.setCustomerName(r.getCustomerName());
					hxOrderPutList.add(hxOrderPutParam);

				}
				this.hxOrderPutService.saveBatch(hxOrderPutList);
				hxOrderPutList.clear();
			}


		}
	}
	}
	//新零帮门店退货单
	@Override
	@Transactional(rollbackFor = Exception.class,timeout=800000)
	public void taskAppointment1() {
		BasicCustomerParam param = new BasicCustomerParam();
		List <BasicCustomerResult> basicCustomerResult = basicCustomerService.findpullReturnXlbListBySpec(param);
		for (BasicCustomerResult r : basicCustomerResult) {
		   if (ToolUtil.isNotEmpty(r.getXlbStorehouseId())) {
			Date date = new Date();
			   LocalDateTime currentTime = LocalDateTime.now().minusHours(3);

			   // 格式化为需要的日期时间字符串
			   DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
			   String formattedDateTime = currentTime.format(formatter);
			   //System.out.println(formattedDateTime);




			   //String url = "https://test-api.xlbsoft.com/api/hxl.open.storeapplicationorder.findbyupdatetime";
			String url = "https://hxl-api.xlbsoft.com/api/hxl.open.storeapplicationorder.findbyupdatetime";


			JSONObject json = new JSONObject();
			json.put("store_id", r.getStoreIdXlb());
			json.put("storehouse_id", r.getXlbStorehouseId());
			json.put("update_time", formattedDateTime);
			BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
			oauth2tokenParam.setDeliverId(r.getDeliverId());
			oauth2tokenParam.setGsnumber(r.getGsnumber());
			BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
			//System.out.println(json.toString());

			String response = HttpRequest.post(url)
					.header("Authorization", "Bearer " + oauth2tokenResult.getOauth2TokenXlb())
					.body(json.toString()).execute().body();
			JSONObject jsonObject = new JSONObject(response);

			if (jsonObject.get("code").toString().equals("0")) {
				JSONArray dataArray = jsonObject.getJSONArray("data");
				List <HxOrderPut> hxOrderPutList = new ArrayList <>();
				List <HxOrderPutDetailed> hxOrderPutDetailedList = new ArrayList <>();
				for (Object data : dataArray) {
					HxOrderPut hxOrderPutParam = new HxOrderPut();
					Object approveBy = ((JSONObject) data).get("approve_by");// 批复人
					Object approveMoney1 = ((JSONObject) data).get("approve_money");// 批复金额
					Object approveTime = ((JSONObject) data).get("approve_time");// 批复时间
					Object auditBy = ((JSONObject) data).get("audit_by");// 审核人
					Object auditTime = ((JSONObject) data).get("audit_time");// 审核时间
					Object companyId = ((JSONObject) data).get("company_id");// 公司id
					Object createBy = ((JSONObject) data).get("create_by");// 创建人
					Object createTime = ((JSONObject) data).get("create_time");// 创建时间

					Object detailsObject = ((JSONObject) data).opt("details"); // 使用 opt 方法获取字段值，避免抛出异常

					if (detailsObject instanceof JSONArray) {
						JSONArray detailsArray = (JSONArray) detailsObject;
						for (Object detail : detailsArray) {
							Object accountMethod = ((JSONObject) detail).get("account_method");// 核算方式
							Object approveBatchNumber = ((JSONObject) detail).get("approve_batch_number");// 批复批次号
							Object approveExpireDate = ((JSONObject) detail).get("approve_expire_date");// 批复过期日期
							Object approveMemo = ((JSONObject) detail).get("approve_memo");// 批复备注
							Object approveMoney = ((JSONObject) detail).get("approve_money");// 批复金额
							Object approvePrice = ((JSONObject) detail).get("approve_price");// 批复单价
							Object approveProducingDate = ((JSONObject) detail).get("approve_producing_date");// 批复生产日期
							Object approveQuantity = ((JSONObject) detail).get("approve_quantity");// 批复数量
							Object approveRatio = ((JSONObject) detail).get("approve_ratio");// 批复换算率
							Object approveUnit = ((JSONObject) detail).get("approve_unit");// 批复单位
							Object basicApprovePrice = ((JSONObject) detail).get("basic_approve_price");// 批复基本单价
							Object basicApproveQuantity = ((JSONObject) detail).get("basic_approve_quantity");// 批复基本数量
							Object basicUnit = ((JSONObject) detail).get("basic_unit");//基本单位
							Object basicPrice = ((JSONObject) detail).get("basic_price");//基本单价
							Object basicQuantity = ((JSONObject) detail).get("basic_quantity");//基本数量
							Object batchId = ((JSONObject) detail).get("batch_id");//批次标识
							Object batchNumber = ((JSONObject) detail).get("batch_number");//批次号
							Object batchNumberFlag = ((JSONObject) detail).get("batch_number_flag");//是否可以选批次
							Object categoryId = ((JSONObject) detail).get("category_id");//分类id
							Object deliveryRatio = ((JSONObject) detail).get("delivery_ratio");//配送单位换算率
							Object deliveryUnit = ((JSONObject) detail).get("delivery_unit");//配送单位
							Object detailNum = ((JSONObject) detail).get("detail_num");//序号
							Object expireDate = ((JSONObject) detail).get("expire_date");//到期日期
							Object expireDateFlag = ((JSONObject) detail).get("expire_date_flag");//是否可以选到期日期
							Object fid = ((JSONObject) detail).get("fid");//单据号
							Object inStorehouseId = ((JSONObject) detail).get("in_storehouse_id");//调入仓库id
							Object inStorehouseName = ((JSONObject) detail).get("in_storehouse_name");//调入仓库
							Object itemBarCode = ((JSONObject) detail).get("item_bar_code");//商品条码
							Object itemCode = ((JSONObject) detail).get("item_code");//商品代码
							Object itemId = ((JSONObject) detail).get("item_id");//商品id
							Object itemName = ((JSONObject) detail).get("item_name");//商品名称
							Object itemSpec = ((JSONObject) detail).get("item_spec");//商品规格
							Object memo = ((JSONObject) detail).get("memo");//备注
							Object period = ((JSONObject) detail).get("period");//保质期
							Object price = ((JSONObject) detail).get("price");//发货单价
							Object producingDate = ((JSONObject) detail).get("producing_date");//生产日期
							Object producingDateFlag = ((JSONObject) detail).get("producing_date_flag");//是否可以选生产日期
							Object purchaseRatio = ((JSONObject) detail).get("purchase_ratio");//采购单位换算率
							Object purchaseUnit = ((JSONObject) detail).get("purchase_unit");//采购单位
							Object ratio = ((JSONObject) detail).get("ratio");//换算率
							Object quantity = ((JSONObject) detail).get("quantity");//数量
							Object shorthandCode = ((JSONObject) detail).get("shorthand_code");// 速记码
							Object stockRatio = ((JSONObject) detail).get("stock_ratio");//库存单位换算率
							Object stockUnit = ((JSONObject) detail).get("stock_unit");//库存单位
							Object supplierFlag = ((JSONObject) detail).get("supplier_flag");//是否可编辑供应商
							Object unit = ((JSONObject) detail).get("unit");//单位
							Object wholesaleRatio = ((JSONObject) detail).get("wholesale_ratio");//批发单位换算率
							Object wholesaleUnit = ((JSONObject) detail).get("wholesale_unit");//批发单位

							HxOrderPutDetailed hxOrderPutDetailedParam = new HxOrderPutDetailed();

							HxBasicGoodsParam hxBasicGoodsParamS = new HxBasicGoodsParam();
							hxBasicGoodsParamS.setGoodsXlbId(itemId.toString());
							hxBasicGoodsParamS.setGoodsCustomerId(r.getId());

							HxBasicGoodsResult goodsid = hxBasicGoodsService.findBySpec(hxBasicGoodsParamS, null);

//						HxBasicGoods goodsid = hxBasicGoodsService.lambdaQuery()
//								.eq(HxBasicGoods::getGoodsXlbId, itemId.toString())
//								.one();

							if (goodsid == null) {
								HxBasicGoods hxBasicGoodsParam = new HxBasicGoods();
								hxBasicGoodsParam.setGoodsXlbId(itemId.toString());
								hxBasicGoodsParam.setGoodsName(itemName.toString());
								hxBasicGoodsParam.setGoodsPcode69(itemBarCode.toString());
								hxBasicGoodsParam.setGoodsNumber(itemCode.toString());
								hxBasicGoodsParam.setGoodsSpecs(itemSpec.toString());
								hxBasicGoodsParam.setJibenUnit(basicUnit.toString());
								hxBasicGoodsParam.setKcUnit(stockUnit.toString());
								hxBasicGoodsParam.setKcRate(String.valueOf(stockRatio));
								hxBasicGoodsParam.setCgUnit(purchaseUnit.toString());
								hxBasicGoodsParam.setCgRate(String.valueOf(purchaseRatio));
								hxBasicGoodsParam.setPfRate(String.valueOf(wholesaleRatio));
								hxBasicGoodsParam.setPfUnit(wholesaleUnit.toString());
								hxBasicGoodsParam.setPsRate(String.valueOf(deliveryRatio));
								hxBasicGoodsParam.setPsUnit(deliveryUnit.toString());
								hxBasicGoodsParam.setCreateTime(new Date());
								hxBasicGoodsParam.setCreateName("系统");
								hxBasicGoodsParam.setDeliverId(r.getDeliverId());
								hxBasicGoodsParam.setDeptId(r.getDeptId());
								hxBasicGoodsParam.setGoodsCustomerName(r.getCustomerName());
								hxBasicGoodsParam.setGoodsCustomerId(r.getId());
								hxBasicGoodsParam.setGoodsBottom("10");
								hxBasicGoodsParam.setGoodsLamination("10");
								hxBasicGoodsParam.setGoodsTraylayer("1");
								hxBasicGoodsParam.setGoodsSupportvolume("100");
								hxBasicGoodsParam.setAnquanNum("14");
								hxBasicGoodsParam.setGoodsWeight("0.1");
								hxBasicGoodsParam.setGoodsChargingCg("10");
								hxBasicGoodsParam.setGoodsChargingPf("10");
								hxBasicGoodsParam.setGoodsChargingPs("10");
								hxBasicGoodsParam.setGoodsVolume("0.1");

								if (ToolUtil.isNotEmpty(period.toString()) && !period.toString().equals("null")) {


									Pattern pattern = Pattern.compile("(\\d+)");
									Matcher matcher = pattern.matcher(period.toString());

									if (matcher.find()) {
										String number = matcher.group(1);
										int periods = Integer.parseInt(number);
										hxBasicGoodsParam.setGoodsWarranty(String.valueOf(periods / 30));
									} else {
										// 未找到匹配的数字
									}
								} else {
									hxBasicGoodsParam.setGoodsWarranty("36");
								}

								hxBasicGoodsService.save(hxBasicGoodsParam);

								hxOrderPutDetailedParam.setGoodsId(hxBasicGoodsParam.getId().longValue());
							} else {

								hxOrderPutDetailedParam.setGoodsId(goodsid.getId().longValue());
							}

							hxOrderPutDetailedParam.setOrderPutNumber(String.valueOf(fid));
							hxOrderPutDetailedParam.setGoodsName(itemName.toString());
							hxOrderPutDetailedParam.setGoodsSpecs(itemSpec.toString());
							hxOrderPutDetailedParam.setGoodsPcode69(itemBarCode.toString());
							hxOrderPutDetailedParam.setGoodsNumber(itemCode.toString());
							hxOrderPutDetailedParam.setNotes(memo.toString());// 备注

							BigDecimal decimal = new BigDecimal(purchaseRatio.toString());
							BigDecimal bigDecimal = new BigDecimal(quantity.toString());
							BigDecimal ratio1 = new BigDecimal(ratio.toString());
							BigDecimal multiply = ratio1.multiply(bigDecimal);
							BigDecimal divide = multiply.divide(decimal, 4, RoundingMode.HALF_DOWN);

							hxOrderPutDetailedParam.setNum(String.valueOf(divide));
							hxOrderPutDetailedParam.setUnit(stockUnit.toString());
							hxOrderPutDetailedParam.setRate(String.valueOf(stockRatio));
							hxOrderPutDetailedParam.setSumNum(String.valueOf(quantity));
							hxOrderPutDetailedParam.setGoodsPrice(String.valueOf(price));
							hxOrderPutDetailedParam.setGoodsSupportvolume("100");
							hxOrderPutDetailedParam.setGoodsWeight("0.1");
							hxOrderPutDetailedParam.setGoodsVolume("0.1");
							hxOrderPutDetailedParam.setUnitType("采购单位");
							hxOrderPutDetailedParam.setXlbOrderPutNumber("");

							if (ToolUtil.isNotEmpty(fid) && !fid.equals("null")) {//单据号
								// 校验是否已经添加过
								Integer count = hxOrderPutDetailedService.lambdaQuery()
										.eq(HxOrderPutDetailed::getOrderPutNumber, fid)
										.count();
								if (count == detailsArray.length()) {
									break; // 如果数据库中已存在该订单号，则跳过当前循环
								}
							}
							hxOrderPutDetailedList.add(hxOrderPutDetailedParam);
						}

					}

					Object fid = ((JSONObject) data).get("fid");// 单据号
					Object handleBy = ((JSONObject) data).get("handle_by");// 处理人
					Object handleMemo = ((JSONObject) data).get("handle_memo");// 处理备注
					Object handleTime = ((JSONObject) data).get("handle_time");// 处理时间
					Object inOrderFid = ((JSONObject) data).get("in_order_fid");// 调入单号
					Object inStoreId = ((JSONObject) data).get("in_store_id");//调往门店id
					Object inStoreName = ((JSONObject) data).get("in_store_name");// 调往门店名称
					Object inStorehouseId = ((JSONObject) data).get("in_storehouse_id");//调入仓库id
					Object inStorehouseName = ((JSONObject) data).get("in_storehouse_name");// 调入仓库名称
					Object itemCount = ((JSONObject) data).get("item_count");// 商品数
					Object memo = ((JSONObject) data).get("memo");// 备注
					Object money = ((JSONObject) data).get("money");// 金额
					Object outOrderFid = ((JSONObject) data).get("out_order_fid");// 调出单号
					Object reason = ((JSONObject) data).get("reason");// 联系方式
					Object state = ((JSONObject) data).get("state");// 状态：INIT(初始化),AUDIT(审核),HANDLE(处理通过),HANDLE_REFUSE(处理拒绝),APPROVE(批复通过),APPROVE_REFUSE(批复拒绝),可用值:APPROVE,APPROVE_REFUSE,AUDIT,HANDLE,HANDLE_REFUSE,INIT
					Object storeId = ((JSONObject) data).get("store_id");// 申请门店id
					Object storeName = ((JSONObject) data).get("store_name");// 门店名称
					Object storehouseId = ((JSONObject) data).get("storehouse_id");// 出货仓库id
					Object storehouseName = ((JSONObject) data).get("storehouse_name");// 仓库名称
					Object type = ((JSONObject) data).get("type");// 申请类型
					Object updateBy = ((JSONObject) data).get("update_by");// 最后修改人
					Object updateTime = ((JSONObject) data).get("update_time");// 最后修改时间


					if (ToolUtil.isNotEmpty(fid) && !fid.equals("null")) {//单据号
						// 校验是否已经添加过
						Integer count = hxOrderPutService.lambdaQuery()
								.eq(HxOrderPut::getOrderPutNumber, fid)
								.ne(HxOrderPut::getOrderState, "作废")
								.count();
						if (count > 0) {
							continue; // 如果数据库中已存在该订单号，则跳过当前循环
						}
					}

					hxOrderPutParam.setOrderPutNumber(String.valueOf(fid));

					if (ToolUtil.isNotEmpty(auditTime.toString()) && !auditTime.toString().equals("null")) {
						hxOrderPutParam.setYuyueTime(auditTime.toString());// 预约时间
					} else {
						SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						String dateString = dateFormat.format(date);
						hxOrderPutParam.setYuyueTime(dateString);// 预约时间
					}

					BasicPutgoods basicPutgoods = basicPutgoodsService.lambdaQuery()
							.eq(BasicPutgoods::getPutgoodsCustomerId, r.getId())
							.eq(BasicPutgoods::getXlbClientId, storeId.toString())
							.eq(BasicPutgoods::getPutgoodsName, storeName.toString())
							.last("limit 1")
							.one();


					BasicWarehouse basicWarehouse = basicWarehouseService.lambdaQuery()
							.eq(BasicWarehouse::getWarehouseOperateId, r.getCustomerOperateId())
							.eq(BasicWarehouse::getWarehouseXlbId, r.getXlbStorehouseId())
							.last("LIMIT 1")
							.one();

					if (basicPutgoods == null) {
						BasicPutgoods bpgp3 = new BasicPutgoods();
						bpgp3.setPutgoodsCustomerId(r.getId());
						bpgp3.setPutgoodsOperateName(r.getCustomerName());
						bpgp3.setPutgoodsName(storeName.toString());//单位名称
						bpgp3.setPutgoodsAddress(storeName.toString());//地点 为单位名称
						bpgp3.setXlbClientId(storeId.toString());
						bpgp3.setUnitType("门店");
						bpgp3.setDictId(0l);
						bpgp3.setDeliverId(r.getDeliverId());
						bpgp3.setDeptId(r.getDeptId());
						basicPutgoodsService.save(bpgp3);
						BasicAddress bap3 = new BasicAddress();


						bap3.setAddress(storeName.toString());//地点 为单位名称
						bap3.setPutgoodsName(storeName.toString());//单位名称
						bap3.setLongitude("0");
						bap3.setLatitude("0");
						bap3.setSwitchWl("1");
						bap3.setSwitchBj("1500");//提货围栏半径 默认100米
						bap3.setSwitchBj2("2000");//收货围栏半径 默认100米
						basicAddressService.save(bap3);

						hxOrderPutParam.setSetUnitId((long) bpgp3.getId());// 发货客户id
					} else {
						hxOrderPutParam.setSetUnitId((long) basicPutgoods.getId());// 发货客户id
					}

//				hxOrderPutParam.setGetUnit(storeName.toString());// 收货门店名称
//				hxOrderPutParam.setGetUnitId((long) basicPutgoods.getId());//收货门店id
					hxOrderPutParam.setSetUnit(storeName.toString());//发货客户

					hxOrderPutParam.setGetWarehouse(basicWarehouse.getWarehouseName());// 收货仓库名称

					hxOrderPutParam.setGetWarehouseId((long) basicWarehouse.getId());//收货仓库id
					hxOrderPutParam.setNotes(memo.toString());// 备注

					hxOrderPutParam.setGoodsNum(itemCount.toString());//商品数
					hxOrderPutParam.setCreateTime(date);// 创建时间

					hxOrderPutParam.setOrderState("待处理");
					if (type.toString().equals("RETURN")) {
						hxOrderPutParam.setOrderType("门店退货");
					}
					if (type.toString().equals("DELIVERY")) {
						hxOrderPutParam.setOrderType("直调申请");
					}
					if (type.toString().equals("TRANSFER")) {
						hxOrderPutParam.setOrderType("门店调拨");
					}
					hxOrderPutParam.setCreateUserName("系统");
					hxOrderPutParam.setXlbOrderId(String.valueOf(fid));
					hxOrderPutParam.setDeptId(r.getDeptId());
					hxOrderPutParam.setDeliverId(r.getDeliverId());
					hxOrderPutParam.setCustomerId((long) r.getId());
					hxOrderPutParam.setCustomerName(r.getCustomerName());
					hxOrderPutList.add(hxOrderPutParam);

				}

				this.hxOrderPutDetailedService.saveBatch(hxOrderPutDetailedList);

				this.hxOrderPutService.saveBatch(hxOrderPutList);
			}
		}
	}
		//System.out.println("定时任务执行成功");
	}

	@Override
	public List <HxOrderPutResult> findlistAllBySpec(HxOrderPutParam hxOrderPutParam, String condition,Long operateId) {
		List<HxOrderPutResult> arrlist = this.baseMapper.findlistAllBySpec(hxOrderPutParam,condition,operateId);
			return arrlist;
	}
	@Override
	public HxOrderPutResult count(HxOrderPutParam hxOrderPutParam, String condition, Long operateId) {
		return this.baseMapper.count(hxOrderPutParam,condition,operateId);
	}
	@Override
	public HxOrderPutResult count1(HxOrderPutParam hxOrderPutParam, String condition, Long operateId) {
		return this.baseMapper.count1(hxOrderPutParam,condition,operateId);
	}
	@Override
	public HxOrderPutResult count2(HxOrderPutParam hxOrderPutParam, String condition, Long operateId) {
		return this.baseMapper.count2(hxOrderPutParam,condition,operateId);
	}

	@Override
	public List <HxOrderPutResult> listAll1(HxOrderPutParam hxOrderPutParam, String condition, Long operateId) {
		List<HxOrderPutResult> arrlist = this.baseMapper.listAll1(hxOrderPutParam,condition,operateId);
		return arrlist;
	}
	@Override
	public List <HxOrderPutResult> list1(HxOrderPutParam hxOrderPutParam, String condition, Long operateId) {
		List<HxOrderPutResult> arrlist = this.baseMapper.list1(hxOrderPutParam,condition,operateId);
		return arrlist;
	}

	@Override
	public List <HxOrderPutResult> List2(HxOrderPutParam hxOrderPutParam, String condition, Long operateId) {
		List<HxOrderPutResult> arrlist = this.baseMapper.list2(hxOrderPutParam,condition,operateId);
		return arrlist;
	}


}
